Power of three¶
Time: O(1); Space: O(1); easy
Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: num = 27
Output: True
Example 2:
Input: num = 0
Output: False
Example 3:
Input: num = 9
Output: True
Example 4:
Input: num = 45
Output: False
Follow up:
Could you do it without using any loop / recursion?
1. Loop Iteration [O(log[b]N), O(1)]¶
2. Base Conversion [O(log[3]N, O(log[3]N]¶
3. Mathematics [Unknown, O(1)]¶
4. Integer Limitations [O(1), O(1)]¶
See also: https://leetcode.com/problems/power-of-three/solution
[2]:
import math
class Solution1(object):
def __init__(self):
# print(int(math.log(0x7fffffff))) # 21
# print(int(math.log(3))) # 1
self.__max_log3 = int(math.log(0x7fffffff) // math.log(3))
self.__max_pow3 = 3 ** self.__max_log3
def isPowerOfThree(self, num) -> bool:
"""
:type num: int
:rtype: bool
"""
return num > 0 and self.__max_pow3 % num == 0
[3]:
s = Solution1()
num = 27
assert s.isPowerOfThree(num) == True
num = 0
assert s.isPowerOfThree(num) == False
num = 9
assert s.isPowerOfThree(num) == True
num = 45
assert s.isPowerOfThree(num) == False